<template>
	<view class="container">
		<view class="login-container">
			<view class="logo">
				<image src="@/static/logo.png" mode="" :style="{ width: 70 + 'rpx', height: 70 + 'rpx' }"></image>
				<text class="title">鑫暖云</text>
			</view>
			<!-- 这块微信登录按钮不删除，上线时解开注释即可 -->
			<!-- <button v-if="showAvatarBtn" class="login-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
				:disabled="loginLoading">
				一键登录
			</button> -->
			<!-- 昵称输入 -->
			<!-- <view class="" v-if="showNicknameInput" style="width:80%;margin:0 auto">
				<input class="nickname-input" type="nickname" placeholder="请输入昵称" v-model="nickName"
					@confirm="onNicknameInput" @blur="onNicknameInput" />
				<button class="login-btn-name" @click="checkLoginReady">确认</button>
			</view> -->
			<button class="login-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
				:loading="loginLoading">
				手机号一键登录
			</button>
			<button class="login-btn cancel" @click="goIndex">
				去首页
			</button>
		</view>

		<uni-popup ref="popupRef" type="bottom" border-radius="20px 20px 0 0">
			<view class="popup-content" v-if="isWeixin">
				<view class="popup-head">
					<image src="@/static/logo.png" mode="" style="width: 30rpx; height: 30rpx"></image>
					<view class=""> 鑫暖云 </view>
					<view class=""> 申请获取 </view>
				</view>
				<view class="popup-get-txt"> 您的个人信息 </view>
				<view class="popup-info">
					<view class="popup-info-left">
						<view class="">
							<image :src="avatarUrl" mode="" style="width: 80rpx; height: 80rpx"></image>
						</view>
						<view class="popup-info-name">
							<view>{{ nickName }}</view>
							<view style="color: #aaaaaa">微信个人信息</view>
						</view>
					</view>
					<view class="popup-info-right">
						<image src="@/static/u665.png" mode="" style="width: 50rpx; height: 50rpx; border-radius: 5rpx">
						</image>
					</view>
				</view>
				<view class="popup-btns">
					<button class="btn-cancel" @click="closePopup('step1')" size="mini">
						取消
					</button>
					<button class="btn-allow" v-if="showPhoneBtn" open-type="getPhoneNumber" size="mini"
						@getphonenumber="getPhoneNumber">
						手机号快捷登录
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		login
	} from "@/api/config.js";
	import {
		ref
	} from "vue";
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		dictKeys
	} from "@/store/dict.js";
	import {
		useUserStore
	} from "@/store/user"; // 导入用户存储
	// 获取用户存储实例
	const userStore = useUserStore();
	// 登录状态
	const loginLoading = ref(false);
	const popupRef = ref(null);
	const isWeixin = ref(true);
	// 用户信息
	const avatarUrl = ref("");
	const nickName = ref("");
	const phoneInfo = ref(null);

	// 控制UI显示
	const showAvatarBtn = ref(true);
	const showNicknameInput = ref(false);
	const showPhoneBtn = ref(true);

	onLoad((e) => {});
	const closePopup = async () => {
		popupRef.value?.close();
		showAvatarBtn.value = true;
		avatarUrl.value = "";
		nickName.value = "";
	};
	// 选择头像
	const onChooseAvatar = (e) => {
		avatarUrl.value = e.detail.avatarUrl;
		showAvatarBtn.value = false;
		showNicknameInput.value = true;
	};
	// 输入昵称
	const onNicknameInput = (e) => {
		nickName.value = e.detail.value;
	};
	const onGetPhoneNumber = async (e) => {
		if (e.detail.errMsg === "getPhoneNumber:ok") {
			phoneInfo.value = e.detail;
			showPhoneBtn.value = false;
			doLogin();
		} else {
			uni.showToast({
				title: "获取手机号失败",
				icon: "none",
			});
			showPhoneBtn.value = true;
		}
	};
	// 检查是否准备好登录
	const checkLoginReady = () => {
		if (avatarUrl.value && nickName.value) {
			uni.setStorageSync("nickname", nickName.value);
			uni.setStorageSync("avatar", avatarUrl.value);
			showNicknameInput.value = false;
			showPhoneBtn.value = true;
			popupRef.value?.open();
		}
	};
	// 执行登录
	const doLogin = async () => {
		try {
			loginLoading.value = true;

			// 获取code
			const loginRes = await uni.login({
				provider: "weixin",
			});

			if (loginRes.errMsg !== "login:ok") {
				throw new Error("获取登录凭证失败");
			}
			// 准备请求数据
			const data = {
				code: loginRes.code,
				avatarUrl: "",
				nickName: "普通用户",
				encryptedData: phoneInfo.value.encryptedData,
				iv: phoneInfo.value.iv,
			};
			uni.$u.http
				.post("/wechat/login", data, {
					header: {
						"Content-Type": "application/json",
					},
				})
				.then((res) => {
					if (res.openid) {
						uni.setStorageSync("openid", res.openid);
						uni.showToast({
							title: "登录成功",
							icon: "success",
						});
						uni.$u.http
							.post("/wechat/getUserInfo", {
								openid: res.openid,
							})
							.then((res) => {
								if (res.success) {
									userStore.setUserInfo(res);
								}
							});
						// 获取微信头像需要上传
						// uni.downloadFile({
						// 	url: avatarUrl.value,
						// 	success: (downloadResult) => {
						// 		if (downloadResult.statusCode === 200) {
						// 			const tempFilePath = downloadResult.tempFilePath;
						// 			console.log(tempFilePath, avatarUrl.value)
						// 			// 3. 使用uni.uploadFile上传文件
						// 			uni.uploadFile({
						// 				url: 'https://dn.xinnuanyun.com/suittc_dn/wechat/uploadAvatar',
						// 				filePath: tempFilePath,
						// 				name: 'avatar',
						// 				formData: {
						// 					openid: res.openid,
						// 					avatar: tempFilePath
						// 				},
						// 				success: (uploadRes) => {
						// 					console.log(JSON.parse(uploadRes.data),
						// 						"上传成功");
						// 				},
						// 				fail: (err) => {
						// 					console.error(err, "上传失败");
						// 				}
						// 			});
						// 		}
						// 	}
						// });

						// 跳转到首页
						setTimeout(() => {
							loginLoading.value = false
							uni.switchTab({
								url: "/pages/index/index",
							});
						}, 1500);
					}
				})
				.catch((e) => {
					console.log(e);
					loginLoading.value = false
				});
		} catch (error) {
			uni.showToast({
				title: error.message || "登录失败",
				icon: "none",
			});
			loginLoading.value = false
		} finally {
			loginLoading.value = false;
		}
	};

	const goIndex = () => {
		uni.switchTab({
			url: "/pages/index/index",
		});
	}
</script>

<style lang="scss" scoped>
	@import "./login.scss";

	.container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background: linear-gradient(200deg, #4f7dbb, #deb9b9);
		color: #464954;
		margin-bottom: 100rpx;
	}

	.login-container {
		width: 80%;
		max-width: 500rpx;
		text-align: center;
		height: 500rpx;
	}

	.logo {
		display: flex;
		justify-content: center;
		align-items: center;

		.title {
			font-size: 50rpx;
			padding-left: 20rpx;
		}
	}

	.login-btn-name {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 80rpx;
		width: 100%;
		padding: 0 20rpx;
		background-color: #02a7f0;
		border-radius: 45rpx;
		color: #fff;
		font-size: 32rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
		transition: all 0.3s;
	}

	.login-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 90rpx;
		background-color: #02a7f0;
		border-radius: 45rpx;
		color: #fff;
		font-size: 32rpx;
		margin-bottom: 40rpx;
		box-shadow: 0 4rpx 12rpx rgba(7, 193, 96, 0.3);
		transition: all 0.3s;
		margin-top: 300rpx;

		&:active {
			transform: scale(0.98);
			box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.2);
		}


	}

	.login-btn.cancel {
		margin-top: 40rpx;
	}

	// 弹出层样式
	.popup-content {
		padding: 15px;
		border-radius: 20px 20px 0 0;
		background-color: #fff;

		button {
			border: none !important;
		}
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 10px;
		border-bottom: 1px solid #eee;
	}

	.popup-body {
		padding: 15px 0;
	}

	.popup-footer {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
		padding-top: 10px;
	}

	.custom-popup-content {
		width: 100%;
		height: 100%;
		background-color: #fff;
		display: flex;
		flex-direction: column;
	}

	.custom-popup-header {
		padding: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #eee;
	}

	.custom-popup-body {
		flex: 1;
		padding: 15px;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 15px;
	}

	.custom-popup-body image {
		width: 80%;
		max-height: 60%;
	}

	.nickname-input {
		width: 100%;
		height: 80rpx;
		margin: 20rpx auto;
		border: 1px solid #eee;
		border-radius: 40rpx;
		background-color: #fff;
	}

	.avatar-btn {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		padding: 0;
		margin: 20rpx auto;
		border: none;

		.avatar-image {
			width: 100%;
			height: 100%;
			border-radius: 50%;
		}
	}
</style>